<template>
  <div class="app-container statistics-goods-page">
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <div>统计图</div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <div style="margin-right: 20px">
          <el-select
            v-model="goodsId"
            placeholder="请选择"
            @change="onSelectChange"
            filterable
          >
            <el-option
              v-for="item in goodsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>

        <div style="margin-right: 20px">
          <el-button type="text" size="small" @click="recentDays(7)"
            >过去7天</el-button
          >
          <el-button type="text" size="small" @click="recentDays(30)"
            >过去30天</el-button
          >
        </div>
        <div>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            unlink-panels
            align="right"
            value-format="timestamp"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="onDateRangeChange"
          >
          </el-date-picker>
        </div>
      </div>
    </div>

    <div style="margin: 20px 0">
      <line-chart
        style="display: inline-block; width: 49%"
        className="order-chart-1"
        yAxisName="该商品的销售额/元"
        :yAxisTitleStyle="{ padding: [0, 0, 0, 60] }"
        :chartData="chartData1"
        @dataPointClick="onDataPointClickC1"
      ></line-chart>

      <line-chart
        style="display: inline-block; width: 49%"
        className="order-chart-2"
        yAxisName="该商品的退费额/元"
        :yAxisTitleStyle="{ padding: [0, 0, 0, 60] }"
        :chartData="chartData2"
        @dataPointClick="onDataPointClickC2"
      ></line-chart>
    </div>

    <Tables ref="tablesRef"></Tables>

    <div style="height: 50px"></div>
  </div>
</template>
<script>
import LineChart from "./components/LineChart";
import Tables from "./components/Tables";
import { myFormatDate } from "@/utils/index.js";
import {
  getSalesAmountStatistics,
  getRefundAmountStatistics,
} from "@/api/statistics/index.js";
import { listGoods } from "@/api/shop/goods";

export default {
  name: "statistics-goods-page",
  components: {
    LineChart,
    Tables,
  },
  props: {},
  computed: {},
  watch: {},
  data() {
    return {
      isLoading: false,
      pickerOptions: {
        onPick: ({ minDate }) => {
          this.minDate = minDate;
        },
        disabledDate: (time) => {
          //查询时间跨度为2个月
          let range = 61 * 24 * 3600 * 1000;
          if (this.minDate) {
            return (
              time.getTime() > Date.now() ||
              time.getTime() > this.minDate.getTime() + range ||
              time.getTime() < this.minDate.getTime() - range
            );
          } else {
            return time.getTime() > Date.now();
          }
        },
      },
      dateRange: [],
      chartData1: {},
      chartData2: {},
      goodsId: null,
      goodsList: [],
    };
  },
  created() {},
  async mounted() {
    await this.getGoodsList();
    // 默认显示最近30天
    this.recentDays(30);
  },
  methods: {
    /**
     * 获取商品数据
     */
    getGoodsList() {
      return new Promise((resolve) => {
        listGoods({ current: 1, size: 9999 }).then((res) => {
          this.goodsList = res.rows;
          // 默认选择第一个
          this.goodsId = this.goodsList[0].id;
          resolve(true);
        });
      });
    },
    /**
     * 获取图表数据
     */
    getChartData() {
      if (!this.dateRange || this.dateRange.length === 0) return;
      if (this.isLoading) return;
      this.isLoading = true;

      let func1 = getSalesAmountStatistics({
        startDate: myFormatDate(new Date(this.dateRange[0]), "yyyy-MM-dd"),
        endDate: myFormatDate(new Date(this.dateRange[1]), "yyyy-MM-dd"),
        id: this.goodsId,
      });
      let func2 = getRefundAmountStatistics({
        startDate: myFormatDate(new Date(this.dateRange[0]), "yyyy-MM-dd"),
        endDate: myFormatDate(new Date(this.dateRange[1]), "yyyy-MM-dd"),
        id: this.goodsId,
      });

      Promise.all([func1, func2]).then((resArr) => {
        if (resArr[0].data) {
          this.chartData1 = this.handleChartData(resArr[0].data, "salesAmount");
        }
        if (resArr[1].data) {
          this.chartData2 = this.handleChartData(
            resArr[1].data,
            "refundAmount"
          );
        }

        this.isLoading = false;
      });
    },
    handleChartData(list, yKeyName) {
      let x = [];
      let y = [];
      list.forEach((v) => {
        x.push(v.date);
        y.push(v[yKeyName]);
      });

      return { x, y };
    },
    /**
     * 获取表格数据
     */
    getTableData() {
      this.$refs.tablesRef.getData(this.dateRange, {
        id: this.goodsId,
      });
    },
    /**
     * 日期选择
     */
    onDateRangeChange() {
      this.minDate = undefined;
      this.getChartData();
      this.getTableData();
    },
    /**
     * 最近x天（包括今天）
     */
    recentDays(days) {
      if (!days) return;

      let today = new Date().getTime();
      let start = today - 3600 * 24 * 1000 * (days - 1); // （包括今天）所以days要减1
      // 同步更新日期组件显示
      this.dateRange = [start, today];
      // 最后再getdata
      this.getChartData();
      this.getTableData();
    },
    /**
     * 修改选项
     */
    onSelectChange(e) {
      this.getChartData();
      this.getTableData();
    },
    /**
     * 图表1点击
     */
    onDataPointClickC1(date) {
      console.log("date: ", date);
    },
    /**
     * 图表2点击
     */
    onDataPointClickC2(date) {
      console.log("date: ", date);
    },
  },
};
</script>
<style lang="scss" scoped>
.statistics-goods-page {
}
</style>
